package cn.t.modules.scheduler.core;

import cn.t.modules.scheduler.common.enums.ScheduleStatus;
import cn.t.modules.scheduler.core.schedule.repository.dao.ScheduleDao;
import cn.t.modules.scheduler.core.schedule.repository.mapper.CreateTableMapper;
import cn.t.modules.scheduler.core.schedule.repository.po.SchedulePo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Set;

/**
 * SQLITE处理器
 * @author 陶敏麒
 * @date 2024/3/6 8:48
 */
@Component
@Slf4j
public class SqlProcessor {

    @Value("${schedule.db.path}")
    private String dbBasePath;
    @Resource
    private ScheduleDao scheduleDao;

    @Resource
    private CreateTableMapper createTableMapper;

    @PostConstruct
    public synchronized void initRequiredTable() {
        // -1. 建表
        File file = new File(this.dbBasePath);
        if (!file.exists()) {
            log.warn(">>>>>>db地址不存在,尝试创建,创建结果:{}",  file.mkdirs());
        }
        log.info(">>>>>>>>>当前本地数据库地址:{}", this.dbBasePath);
        this.createTableMapper.createScheduleTable();
        // 建立索引
        this.createTableMapper.createScheduleIndex();
    }

    /**
     * 保存调度计划
     */
    public void saveSchedule(SchedulePo schedulePo) {
        if (!StringUtils.hasText(schedulePo.getSrc())) {
            schedulePo.setSrc("system");
        }
        this.scheduleDao.save(schedulePo);
    }

    public List<SchedulePo> queryScheduleList(String scheduleId, ScheduleStatus status) {
        return this.scheduleDao.lambdaQuery()
                .eq(SchedulePo::getStatus, status)
                .eq(SchedulePo::getScheduleId, scheduleId).list();
    }

    /**
     * 查询一分钟后即将到期的计划
     */
    public List<SchedulePo> queryAcceptedScheduleList(int limit) {
        return this.scheduleDao.queryAcceptedScheduleList(limit);
    }

    public void updateStatus(long id, ScheduleStatus scheduleStatus, String desc, int version) {
        this.scheduleDao.updateStatus(id, scheduleStatus, desc, version);
    }

    public void updateStatusBatch(Set<Long> ids, ScheduleStatus scheduleStatus, String desc) {
        this.scheduleDao.updateStatusBatch(ids, scheduleStatus, desc);
    }

    /**
     * 指定的数据是否变更过
     */
    public boolean hasChanged(long id, int version, ScheduleStatus scheduleStatus) {
        return this.scheduleDao.hasChanged(id, version, scheduleStatus);
    }

    /**
     * 清理执行过的历史数据
     * @param clearTimeTs 指定时间点
     */
    public void clearScheduleHistory(long clearTimeTs) {
        this.scheduleDao.clearScheduleHistory(clearTimeTs);
    }
}
